<template>
    <el-container style="display: flex; justify-content: center; height: 100%">
        <el-card class="box-card">
            <!-- 表单区域 -->
            <el-form :model="searchForm" inline class="search-form">
                <el-row :gutter="20" type="flex" justify="space-between" align="middle">
                    <el-col :span="16">
                        <el-form-item label="赛项" style="width: 40vh;">
                            <el-select v-model="selectedMatchId" placeholder="请选择" @change="onMatchChange">
                                <el-option value="">全部</el-option>
                                <el-option v-for="item in match" :key="item.id" :label="item.title" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="">
                            <el-input v-model="searchQuery" placeholder="输入队伍名称" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary">
                                查询
                            </el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item class="text-right">
                            <el-input v-model="reviseteam" placeholder="请输入操作团队的序号"></el-input>
                            <el-button type="primary" @click="addEvents">
                                操作团队
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- 表格区域 -->
            <el-table :data="filteredTableData" border style="width: 100%">
                <el-table-column prop="id" label="序号" width="80" />
                <el-table-column label="队伍名称" width="220">
                  <template #default="{ row }">
                    <RouterLink :to="`/admin/Reportordeclare/${row.id}`">{{ row.teamName }}</RouterLink>
                  </template>
                </el-table-column>
                <el-table-column prop="teamAbbreviation" label="队伍简称" width="150" />
                <el-table-column prop="address" label="地址" />
                <el-table-column prop="teamLeader" label="负责人" width="150" />
                <el-table-column prop="phone" label="联系电话" width="150" />
                <el-table-column prop="email" label="邮箱" width="220" />
                <el-table-column prop="image" label="责任书" width="150">
                    <template #default="{ row }">
                        <img :src="serverUrl + row.image" alt="Team Image" style="width: 50px; height: 50px; object-fit: cover;" />
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </el-container>
    <el-dialog title="操作团队" v-model="dialogVisible" width="30%" @close="dialogVisible = false">
    <el-form :model="editForm">
      <el-form-item label="团队名称">
        <el-input v-model="editForm.teamName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="editForm.address" placeholder="请输入身份证号"></el-input>
      </el-form-item>
      <el-form-item label="负责人">
        <el-input v-model="editForm.teamLeader" placeholder="请输入出生年月"></el-input>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="editForm.phone" placeholder="请输入性别"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="editForm.email" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="责任书">
        <el-upload class="avatar-uploader" action="http://back1.idcfengye.com:15173/competition/upload" :show-file-list="false"
          :http-request="customUpload" :before-upload="beforeUpload">
          <img v-if="editForm.image" :src="serverUrl + editForm.image" class="avatar" style="width: 150px;">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          <el-button link icon="el-icon-delete" @click="deletePhoto" v-if="editForm.image">删除照片</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit">提交修改</el-button>
      <el-button type="primary" @click="handleSubmit">删除团队</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { RouterLink } from 'vue-router';

const noimage = ref('');
const token = localStorage.getItem('adminToken');
const searchForm = ref({});
const searchQuery = ref('');
const tableData = ref([]);
const match = ref([]);
const selectedMatchId = ref('');
const reviseteam = ref('');
const dialogVisible = ref(false); // 控制对话框显示与隐藏
const editForm = ref({})

const serverUrl = ref('http://back1.idcfengye.com:15173');

// 查询所有比赛的队伍的数据
async function fetchTeamData() {
    try {
        const response = await axios.get('http://back1.idcfengye.com:15173/api/getAllTeam', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        tableData.value = response.data.data; // 确保后端返回的数据结构与此匹配
    } catch (error) {
        console.log(error);
    }
}

// 查询所有比赛的数据
async function fetchMatchData() {
    try {
        const response = await axios.get('http://back1.idcfengye.com:15173/competition/match', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        match.value = response.data.matches || []; // 确保后端返回的数据结构与此匹配，如果为空则设为空数组
    } catch (error) {
        console.log(error);
    }
}


onMounted(() => {
    fetchMatchData();
    fetchTeamData();
});

// 计算属性：根据选中的赛项ID和搜索查询来过滤数据
const filteredTableData = computed(() => {
    return tableData.value.filter(team => {
        const matchCondition = !selectedMatchId.value || team.matchId === selectedMatchId.value;
        return matchCondition && (!searchQuery.value || team.teamName.toLowerCase().includes(searchQuery.value.toLowerCase()));
    });
});


function onMatchChange() {
    // 重新加载数据
    fetchTeamData();
}

//操作团队的逻辑
function addEvents() {
  if (reviseteam.value === '') {
    ElMessage.error('请选择要操作的人员的序号');
    return;
  }

  // 将 revisestaff.value 转换为数字
  const index = parseInt(reviseteam.value);

  // 使用 find 方法查找对应的人员信息
  const table = tableData.value.find(item => item.id === index);

  if (!table) {
    ElMessage.error('未找到对应的人员信息');
    return;
  }

  editForm.value = table; // 将找到的人员信息赋值给 editForm
  dialogVisible.value = true; // 显示对话框
}

// 自定义上传方法
const customUpload = async (file) => {
  const formData = new FormData();
  formData.append('file', file.file);

  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/upload', formData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });
    if (response.data.success) {
      editForm.value.image = response.data.path;
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error('图片上传失败');
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('图片上传失败');
  }
};

// 上传前的检查
const beforeUpload = (file) => {
  // 可以在这里添加文件类型和大小的检查
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
    return false;
  }
  // 可以添加文件大小的检查
  return isImage;
};

// 删除 '/upload/' 的函数
function removeUploadPath(filePath) {
  return filePath.replace('/upload/', '');
}

// 删除照片的方法
const deletePhoto = async () => {
  noimage.value = editForm.value.image;
  const cleanedImagePath = removeUploadPath(noimage.value);
  try {
    // 调用后端接口删除服务器上的照片
    await axios.delete(`http://back1.idcfengye.com:15173/competition/delete/${cleanedImagePath}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    // 从 editForm 中移除照片 URL
    editForm.value.image = '';
    ElMessage.success('照片删除成功');
  } catch (error) {
    console.error(error);
    if (error.code === 'ERR_NETWORK') {
      ElMessage.error('网络请求失败，请检查你的网络连接或服务器状态。');
    } else {
      ElMessage.error('删除失败：' + error.message);
    }
  }
}

// 编辑团队信息
async function submitEdit() {
    try{
        const response = await axios.put('http://back1.idcfengye.com:15173/competition/teamgroup', editForm.value, {
            headers:{
                'Authorization': `Bearer ${token}`
            }
        })
        if(response.data.success){
            ElMessage.success('修改成功');
            reviseteam.value = ''
            editForm.value = {}
            dialogVisible.value = false
            
        }
    }catch(error){
        if(error.response && error.response.data){
            ElMessage.error(error.response.data.message || '修改失败');
        }
    }
}

// 删除团队信息
async function deleteTeam() {
    const teamid = editForm.value.id;
    try{
        const response = await axios.delete(`http://back1.idcfengye.com:15173/competition/teamgroup/${teamid}`,  {
            headers:{
                'Authorization': `Bearer ${token}`
            }
        })
        if(response.data.success){
            ElMessage.success('删除成功');
            reviseteam.value = ''
            editForm.value = {}
            dialogVisible.value = false
        }
    }catch(error){
        if(error.response && error.response.data){
            ElMessage.error(error.response.data.message || '删除失败');
        }
    }
}

// 删除团队再确认
const handleSubmit = async () => {
  ElMessageBox.confirm(`您确定要删除`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteTeam();
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除'
    });
  });
};
</script>

<style scoped>

</style>